package com.itheima.filter;


import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter("/*")
@Slf4j
public class AuthFilter implements Filter {

    @Override //初始化方法，只会被执行一次
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("AuthFilter初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求的url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURL().toString();
        log.info("url:{}", url);
        //是否包含login,如果包含，则放行
        if (url.contains("login")) {
            log.info("登录操作，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 获取请求的token
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
//            response.setStatus(401);
            log.info("token为空，请登录");
            Result error = Result.error("token not login");
            //在过滤器中，手动将结果输出到前端
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        // 解析token
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token解析失败");
            Result error = Result.error("not token");
            //在过滤器中，手动将结果输出到前端
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
        // 放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override //销毁方法，只会被执行一次
    public void destroy() {
        Filter.super.destroy();
        log.info("AuthFilter销毁");
    }
}
